
import { ROOT } from '@sker/core';
import { useAddonSetting } from '@sker/runtime';
import { Connection, connect } from 'amqplib';
import { join } from 'path';
import { DependencyContainer } from 'tsyringe';
export interface MqHandler {
    (conn: Connection): Promise<void>;
}
let conn: Promise<Connection>;
const createMq = async (injector: DependencyContainer,) => {
    if (conn) return conn;
    const root = injector.resolve(ROOT)
    const env = injector.resolve<any>('ENV')
    let config: any = {
        url: env.MQ_URL,
    };
    let mqSetting = await useAddonSetting('@imeepos/mq').catch(e => {
        return;
    })
    if (mqSetting) {
        config.url = mqSetting.url || config.url;
    }
    if (!config) {
        const jsonFile = join(`${root}`, 'data/plugins', `@sker/mq.json`)
        config = require(jsonFile)
    }
    conn = connect(config.url)
    return conn;
}
export const useMq = async (injector: DependencyContainer, handler: MqHandler) => {
    const con = await createMq(injector)
    con.on('error', e => {
        console.error(e)
        conn = null;
    })
    const res = await handler(con);
    return res;
}
export const test = async (injector: DependencyContainer) => {
    const now = Date.now()
    await useMq(injector, async (con) => { })
    return { success: true, message: 'ok', data: `${(Date.now() - now) / 1000}s` };
}
export default useMq;
